using Cysharp.Threading.Tasks;
using Framework.StateMechine;
using UnityEngine;

namespace Game.Hotfix
{
    public class HotfixVerifyVersion : StateBase
    {
        private Game.Hotfix.Hotfix hotfix;
        
        public override async UniTask OnEnter(StateArgs _args)
        {
            Debug.Log("verify version.");
            
            hotfix = stateMachine.owner as Game.Hotfix.Hotfix;
            await base.OnEnter(_args);
            
            // 对比当前热更版本和原始资源版本
            if (hotfix.hotfixVersion < hotfix.engineVersion)
            {
                // 覆盖安装
                FileHelper.DeletDir(FileHelper.hotfixFolder);
                hotfix.hotfixVersion = hotfix.engineVersion;
            }
            
            // 对比原始版本和服务器当前配置的最小版本
            if (hotfix.engineVersion < hotfix.hotfixServerDto.minVersion)
            {
                // 包内原始版本号小于最小服务器资源版本，则需下载安装新版本客户端
                stateMachine.Change(HotfixState.Reinstall);
                return;
            }
            
            // 热更完毕，或者无需更新
            if (hotfix.hotfixVersion >= hotfix.hotfixServerDto.version)
            {
                // 已经更到最新版本
                Debug.Log("[HotfixPrepare] client is neweaset, no need to update");
                if (hotfix.engineVersion > hotfix.hotfixVersion)
                    FileHelper.DeletDir(FileHelper.hotfixFolder);
                
                // 热更完成
                stateMachine.Change(HotfixState.End);
                return;
            }
            
            stateMachine.Change(HotfixState.LoadChecksum);
        }
    }
}